<template>
    <div class="step-section-item">
        <div class="step-section-item__label">主体类型</div>
        <div class="zent-form-control">
            <RadioType
                v-model:modelValue="formState.base_data.type"
                :radioList="[{ key: 1, title: '个人' },{ key: 2, title: '企业' }]"></RadioType>
            <div class=" cert-type-desc-principal">
                <template v-if="formState.base_data.type==2">
                    “企业”在营业执照上的主体类型一般为：有限公司、有限责任公司等。
                </template>
                <template v-else>
                    “个人”为根据法律法规和相关规定免于办理工商登记，无营业执照的商家。
                </template>
            </div>
        </div>
    </div>
    <el-form v-if="!loading" ref="formStateRef" :model="formState" label-width="auto">
        <el-form-item :rules="[{ required: true, message: adminType?'请选择管理员':'请选择会员' }]" prop="admin.user_id" :label="adminType?'绑定管理员':'绑定会员'">
            <el-select
                v-model="formState.admin.user_id"
                filterable
                remote
                reserve-keyword
                :placeholder="adminType?'可输入手机号查询绑定管理员':'可输入手机号查询绑定会员'"
                :remote-method="remoteMethod"
                :loading="loadingVal"
            >
                <el-option v-for="item in userInfo"
                           :key="item.key"
                           :label="item.label"
                           :value="item.value"
                />
            </el-select>
            <div class="extra">必须绑定一位{{ adminType ? "「管理员」" : "「会员」" }}，您也可以绑定一位
                <span class="font-color" @click="adminType = !adminType"> {{ !adminType ? "管理员" : "会员" }}</span>。
            </div>
        </el-form-item>
        <el-tabs v-model="activeKey" class="lyecs-tabs" tab-position="top" @tab-change="onTabChange">
            <el-tab-pane :key="3" :label="formState.base_data.type==1?'个人信息':'法人代表信息'" name="base">
                <el-form-item :rules="[{ required: true, message: '请选择证件类型!' }]" label="证件类型" prop="base_data.document_type">
                    <el-select v-model="formState.base_data.document_type" placeholder="请选择证件类型">
                        <el-option v-for="item in documentTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item :label="formState.base_data.type==1?'姓名':'法定代表人姓名'" :rules="[{ required: true, message: '请输入'+(formState.base_data.type==1?'姓名':'法定代表人姓名')+'!' }]" prop="base_data.corporate_name">
                    <el-input v-model="formState.base_data.corporate_name"></el-input>
                    <div v-if="formState.base_data.document_type==2" class="extra">填写中文名（英文名），如“张三（Zhang San）”</div>

                </el-form-item>
                <el-form-item :rules="[{ required: true, message: '请输入证件号码!' }]" label="证件号码" prop="base_data.document_number">
                    <el-input v-model="formState.base_data.document_number"></el-input>
                </el-form-item>
                <el-form-item :rules="[{ required: true, message: '请选择出生日期!' }]" label="出生日期" prop="base_data.birthday">
                    <el-date-picker
                        v-model="formState.base_data.birthday"
                        placeholder="请选择出生日期"
                        style="width: 100%"
                        type="date"
                        value-format="YYYY-MM-DD"
                    />
                </el-form-item>
                <el-form-item>
                    <template #label>
                        <span class="required">*</span> 证件有效期：
                    </template>
                    <div class="one-item">
                        <div class="to-time">
                            <el-radio-group v-model="formState.base_data.certificate_validity_period">
                                <el-radio :value="1">区间有效</el-radio>
                            </el-radio-group>
                            <el-form-item :rules="(formState.base_data.certificate_validity_period===1?[{ required: true, message: '请选择日期!' }]:[])" label="" prop="base_data.certificate_validity_period_date">
                                <el-date-picker
                                    v-model="formState.base_data.certificate_validity_period_date"
                                    :clearable="false"
                                    :disabled="formState.base_data.certificate_validity_period===2"
                                    end-placeholder="结束日期"
                                    range-separator="～"
                                    start-placeholder="开始日期"
                                    type="daterange"
                                    value-format="YYYY-MM-DD"
                                />
                            </el-form-item>
                        </div>
                        <div class="to-time">
                            <el-radio-group v-model="formState.base_data.certificate_validity_period">
                                <el-radio :value="2">长期有效</el-radio>
                            </el-radio-group>
                            <el-form-item :rules="(formState.base_data.certificate_validity_period===2?[{ required: true, message: '请选择日期!' }]:[])" label="" prop="base_data.certificate_validity_period_end">
                                <el-date-picker
                                    v-model="formState.base_data.certificate_validity_period_end"
                                    :clearable="false"
                                    :disabled="formState.base_data.certificate_validity_period===1"
                                    placeholder="请选择日期"
                                    style="width: 168px"
                                    type="date"
                                    value-format="YYYY-MM-DD"
                                />
                                <span class="ml10">～ 长期</span>
                            </el-form-item>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item :rules="[{ required: true, message: '请输入居住地址!' }]" label="居住地址" prop="base_data.residential_address">
                    <el-input :autosize="{ minRows: 2, maxRows:6 }" v-model="formState.base_data.residential_address" placeholder="请输入居住地址" type="textarea"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="formState.base_data.sex">
                        <el-radio :value="1">男</el-radio>
                        <el-radio :value="2">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item :rules="[{ required: true, message: '请上传证件照正面!' }]" label="证件照正面" prop="base_data.front_of_photo_temp">
                    <FormAddGallery v-model:photo="formState.base_data.front_of_photo_temp"></FormAddGallery>
                    <div class="extra">
                        <p>如你的证件类型是身份证，请在此处上传人像面，若为复印件，需加盖公司鲜章。注意：证件盖章不支持电子章。</p>
                        <p>护照需要增加翻译件，加盖公司鲜章，外籍商家姓名需为中文（英文），如张三（Zhangsan）。</p>
                    </div>
                </el-form-item>
                <el-form-item :rules="[{ required: true, message: '请上传证件照反面!' }]" label="证件照反面" prop="base_data.back_of_photo_temp">
                    <FormAddGallery v-model:photo="formState.base_data.back_of_photo_temp"></FormAddGallery>
                    <div class="extra">
                        <p>如你的证件类型是身份证，请在此处上传国徽面，若为复印件，需加盖公司鲜章。注意：证件盖章不支持电子章。</p>
                        <p>护照需要增加翻译件，加盖公司鲜章，外籍商家姓名需为中文（英文），如张三（Zhangsan）。</p>
                    </div>
                </el-form-item>
                <el-form-item label="补充信息">
                    <FormAddGallery :isMultiple="true" v-model:photos="formState.base_data.supplementary_information"></FormAddGallery>
                    <div class="extra">
                        <p>在整个申请流程中，遇到需提供资料但无上传入口的情况，都可在此处上传。</p>
                        <p>必须为彩色图片（文档请截图后上传）。</p>
                    </div>
                </el-form-item>
            </el-tab-pane>
            <el-tab-pane :key="4" label="商户信息" name="merchant">
                <el-form-item :rules="[{ required: true, message: '请输入商户名称!' }]" label="商户名称" prop="merchant_data.merchant_name">
                    <el-input v-model="formState.merchant_data.merchant_name" class="item-width"></el-input>
                    <div class="extra">
                        该名称将在微信支付、支付宝支付时向买家展示
                    </div>
                </el-form-item>
                <el-form-item :rules="[{ required: true, message: '请输入客服电话!' }]" label="客服电话" prop="merchant_data.customer_service_phone">
                    <el-input v-model="formState.merchant_data.customer_service_phone" class="item-width"></el-input>
                    <div class="extra">
                        请注意填写格式，举例（座机：0755-88880000；手机：13688880000；400电话：4008880000）
                    </div>
                </el-form-item>
                <el-form-item :rules="[{ required: true, message: '请选择经营地址!' }]" label="经营地址" prop="merchant_data.business_address">
                    <SelectRegion v-if="!loading" v-model="formState.merchant_data.business_address"></SelectRegion>
                </el-form-item>
                <el-form-item :rules="[{ required: true, message: '请输入详细地址!' }]" label="详细地址" prop="merchant_data.detailed_address">
                    <el-input v-model="formState.merchant_data.detailed_address" class="item-width" placeholder="请输入详细地址" type="textarea"></el-input>
                    <div class="extra">
                        请填写详细的经营场所地址，如有多个场所，选择一个主要场所填写即可
                    </div>
                </el-form-item>
                <el-form-item v-if="formState.base_data.type==2" :rules="[{ required: true, message: '请上传营业执照!' }]" label="营业执照电子版" prop="merchant_data.business_license_img_temp">
                    <FormAddGallery v-model:photo="formState.merchant_data.business_license_img_temp"></FormAddGallery>
                    <div class="extra">
                        必须为彩色图片且小于2M，若为复印件，需加盖公司红章。
                    </div>
                </el-form-item>


                <el-form-item :rules="[{ required: true, message: '请输入联系人姓名!' }]" label="联系人姓名" prop="merchant_data.contact_name">
                    <el-input v-model="formState.merchant_data.contact_name"></el-input>
                    <div class="extra">
                        请填写联系人姓名
                    </div>
                </el-form-item>
                <el-form-item :rules="[{ required: true, message: '请输入联系人手机!' }]" label="联系人手机" prop="merchant_data.contact_phone">
                    <el-input v-model="formState.merchant_data.contact_phone"></el-input>
                    <div class="extra">
                        非常重要，此手机号将作为后续登录商户系统的账号
                    </div>
                </el-form-item>
                <el-form-item :rules="[{ required: true, message: '请输入联系人邮箱!' }]" label="联系人邮箱" prop="merchant_data.contact_email">
                    <el-input v-model="formState.merchant_data.contact_email"></el-input>
                </el-form-item>
                <el-form-item :rules="[{ required: true, message: '请输入开户银行!' }]" label="开户银行" prop="merchant_data.bank_deposit">
                    <el-input v-model="formState.merchant_data.bank_deposit"></el-input>
                </el-form-item>
                <el-form-item :rules="[{ required: true, message: '请输入支行名称!' }]" label="支行名称" prop="merchant_data.bank_branch">
                    <el-input v-model="formState.merchant_data.bank_branch"></el-input>
                </el-form-item>
                <el-form-item :label="formState.base_data.type==1?'银行卡号':'对公银行账户'" :rules="[{ required: true, message: '请输入'+(formState.base_data.type===1?'银行卡号':'对公银行账户')+'!' }]" prop="merchant_data.bank_card">
                    <el-input v-model="formState.merchant_data.bank_card"></el-input>
                </el-form-item>
                <el-form-item :rules="[{ required: true, message: '请上传开户许可证!' }]" label="开户许可证" prop="merchant_data.account_opening_permit_temp">
                    <FormAddGallery v-model:photo="formState.merchant_data.account_opening_permit_temp"></FormAddGallery>
                    <div class="extra">
                        开户许可证/基本存款账户任选其一上传，信息需与填写的结算账户信息一致，如无法提供，上传银行对公账户开户业务办理回执，或网银截图，或企业盖章的对公账户信息文件即可
                    </div>
                </el-form-item>

            </el-tab-pane>
            <el-tab-pane v-if="formState.base_data.type==2" :key="2" :label="'企业信息'" name="company">
                <el-form-item :rules="[{ required: true, message: '请输入企业名称!' }]" class="form-item" label="企业名称" prop="base_data.company_name">
                    <el-input v-model="formState.base_data.company_name" class="item-width"></el-input>
                </el-form-item>
                <el-form-item :rules="[{ required: true, message: '请选择注册地址!' }]" class="form-item" label="注册地址" prop="base_data.license_addr_province">
                    <SelectRegion v-if="!loading" v-model="formState.base_data.license_addr_province"></SelectRegion>
                </el-form-item>
                <el-form-item :rules="[{ required: true, message: '请输入详细地址!' }]" class="form-item" label="详细地址" prop="base_data.business_license_address">
                    <el-input :autosize="{ minRows: 2, maxRows:6 }" v-model="formState.base_data.business_license_address" class="item-width" type="textarea"></el-input>
                    <div class="extra">
                        注册地址需与营业执照登记住所一致
                    </div>
                </el-form-item>
                <el-form-item :rules="[{ required: true, message: '请输入经营范围!' }]" class="form-item" label="经营范围" prop="base_data.business_scope">
                    <el-input :autosize="{ minRows: 2, maxRows:6 }" v-model="formState.base_data.business_scope" class="item-width" type="textarea"></el-input>
                    <div class="extra">
                        与企业工商营业执照上一致
                    </div>
                </el-form-item>
                <el-form-item :rules="[{ required: true, message: '请输入统一社会信用代码!' }]" class="form-item" label="统一社会信用代码" prop="base_data.business_license_id">
                    <el-input v-model="formState.base_data.business_license_id" class="item-width"></el-input>
                    <div class="extra">
                        请输入营业执照上18位统一社会信用代码
                    </div>
                </el-form-item>
                <el-form-item class="form-item">
                    <template #label>
                        <span class="required">*</span> 营业期限：
                    </template>
                    <div class="one-item">
                        <div class="to-time">
                            <el-radio-group v-model="formState.base_data.operating_term_type">
                                <el-radio :value="1">区间有效</el-radio>
                            </el-radio-group>
                            <el-form-item :rules="(formState.base_data.operating_term_type===1?[{ required: true, message: '请选择日期!' }]:[])" label="" prop="base_data.operating_term_type_date">
                                <el-date-picker
                                    v-model="formState.base_data.operating_term_type_date"
                                    :clearable="false"
                                    :disabled="formState.base_data.operating_term_type===2"
                                    end-placeholder="结束日期"
                                    range-separator="～"
                                    start-placeholder="开始日期"
                                    type="daterange"
                                    value-format="YYYY-MM-DD"
                                />
                            </el-form-item>
                        </div>
                        <div class="to-time">
                            <el-radio-group v-model="formState.base_data.operating_term_type">
                                <el-radio :value="2">长期有效</el-radio>
                            </el-radio-group>
                            <el-form-item :rules="(formState.base_data.operating_term_type===2?[{ required: true, message: '请选择日期!' }]:[])" label="" prop="base_data.operating_term_type_end">
                                <el-date-picker
                                    v-model="formState.base_data.operating_term_type_end"
                                    :clearable="false"
                                    :disabled="formState.base_data.operating_term_type===1"
                                    placeholder="请选择日期"
                                    style="width: 168px"
                                    type="date"
                                    value-format="YYYY-MM-DD"
                                />
                                <span class="ml10">～ 长期</span>
                            </el-form-item>
                        </div>
                    </div>
                </el-form-item>
            </el-tab-pane>
        </el-tabs>
        <el-form-item v-show="!props.isDialog" :wrapper-col="{ offset: 4, span: 16 }">
            <el-button ref="submitBtn" class="form-submit-btn" type="primary" @click="onSubmit">提交</el-button>
        </el-form-item>
    </el-form>
    <a-spin :spinning="loading" style="width:100%;margin-top:100px" />
</template>
<script setup lang="ts">
import { ref, shallowRef, watch } from "vue";
import { RadioType } from "@/components/radio";

import { MerchantFormState } from "@/types/adminMerchant/merchant";
import { message } from "ant-design-vue";
import { FormAddGallery } from "@/components/gallery";
import { SelectRegion } from "@/components/select";
import { PicList } from "@/components/decorate";
import { updateMerchant } from "@/api/adminMerchant/merchant";
import { useRouter } from "vue-router";
import { getAdminUserList, getAdminUserSearch } from "@/api/authority/adminUser";
import { getUserList } from "@/api/user/user";

const activeKey = ref<string>("base");
const onTabChange = (val: string) => {
    activeKey.value = val;
};
const loading = ref<boolean>(false);

const formState = ref<MerchantFormState>(
    {
        admin: {
            user_id: null,
            type: 1,
            admin_id: null
        },
        base_data: {
            type: 1,
            certificate_validity_period: 1,
            operating_term_type: 1,
            front_of_photo: [],
            back_of_photo: [],
            license_addr_province: [],
            supplementary_information: []
        },
        merchant_data: {
            business_address: [],
            account_opening_permit: [],
            business_license_img: []
        }
    }
);
const loadingVal = ref(false);
const adminType = ref(true);
const userInfo = ref<any>([]);
const remoteMethod = async (query: string) => {
    try {
        if (query) {
            loadingVal.value = true;
            const params = { keyword: query };

            // 使用公共方法来获取数据
            const result = await getUserFetch(params);

            // 设置用户信息
            result.filter_result.forEach((item: any) => {
                if(adminType.value){
                    item.value = item.admin_id;
                    item.key = item.admin_id;
                }else{
                    item.value = item.user_id;
                    item.key = item.user_id;
                }
                item.label = item.username;
            });
            userInfo.value = result.filter_result;
        } else {
            userInfo.value = [];
        }
    } catch (error: any) {
        message.error(error.message);
    } finally {
        loadingVal.value = false;
    }
};
const getUserFetch = async (params: { keyword: string }) => {
    if (adminType.value) {
        return await getAdminUserList(params);
    } else {
        return await getUserList(params);
    }
};
//证件类型
const documentTypeOptions = ref([
    {
        value: 1,
        label: "大陆身份证"
    }, {
        value: 2,
        label: "护照（限境外人士）"
    }, {
        value: 3,
        label: "来往内地通行证（中国香港居民）"
    }, {
        value: 4,
        label: "来往内地通行证（中国澳门居民）"
    }, {
        value: 5,
        label: "来往大陆通行证（中国台湾居民）"
    }
]);
const formStateRef = shallowRef();
//日期选择校验重置
watch(
    () => formState.value.base_data.certificate_validity_period,
    (val) => {
        if (val == 1) {
            formStateRef.value?.clearValidate("base_data.certificate_validity_period_end");
        } else {
            formStateRef.value?.clearValidate("base_data.certificate_validity_period_date");
        }
    }, { deep: true }
);
watch(
    () => formState.value.base_data.operating_term_type,
    (val) => {
        if (val == 1) {
            formStateRef.value?.clearValidate("base_data.operating_term_type_end");
        } else {
            formStateRef.value?.clearValidate("base_data.operating_term_type_date");
        }
    }, { deep: true }
);
//身份证自动填充
watch(
    () => formState.value.base_data.document_number,
    (val) => {
        if (formState.value.base_data.document_type == 1 && val.length >= 18) {
            let temp = val.substr(6, 8);
            formState.value.base_data.birthday = temp.slice(0, 4) + "-" + temp.slice(4, 6) + "-" + temp.slice(6, 8);
            let genderIndicator = parseInt(val.substr(val.length - 2, 1), 10);
            formState.value.base_data.sex = (genderIndicator % 2 === 0) ? 2 : 1;
        }

    },
    { deep: true }
);
watch(() => formState.value.base_data.type, (val) => {
    console.log(val);
    console.log(activeKey.value);
    if (activeKey.value == "company") {
        if (val == 1) {
            activeKey.value = "base";
        }
    }
});
const props = defineProps({
    id: {
        type: Number,
        default: 0
    },
    act: {
        type: String,
        default: ""
    },
    isDialog: Boolean
});
const query = useRouter().currentRoute.value.query;
const action = ref<string>(props.isDialog ? props.act : String(query.act));
const id = ref<number>(props.isDialog ? props.id : Number(query.id));
const operation = action.value === "add" ? "create" : "update";
const emit = defineEmits(["submitCallback", "update:confirmLoading", "close"]);
// 表单通过验证后提交
const onSubmit = async () => {
    await formStateRef.value.validate();
    try {
        emit("update:confirmLoading", true);

        formState.value.base_data.front_of_photo = [{pic_url:formState.value.base_data.front_of_photo_temp}]
        formState.value.base_data.back_of_photo = [{pic_url:formState.value.base_data.back_of_photo_temp}]
        formState.value.merchant_data.business_license_img = [{pic_url:formState.value.merchant_data.business_license_img_temp}]
        formState.value.merchant_data.account_opening_permit = [{pic_url:formState.value.merchant_data.account_opening_permit_temp}]

        let tempData: any = {
            ...formState.value,
            admin:{
                type: adminType?2:1,
                user_id: formState.value.admin.user_id,
                admin_id: formState.value.admin.user_id
            },
            shop_title: formState.value.merchant_data.merchant_name,
            type: formState.value.base_data.type
        };
        //处理图片
        const result = await updateMerchant(operation, { ...tempData });
        emit("submitCallback", result);
        message.success(result.message);
    } catch (error: any) {
        message.error(error.message);
    } finally {
        emit("update:confirmLoading", false);
    }
};
// 表单提交
const onFormSubmit = () => {
    onSubmit();
};

defineExpose({ onFormSubmit });
</script>
<style scoped lang="less">
.step-section-item {
    display: flex;
    margin-bottom: 24px;

    .step-section-item__label {
        margin-right: 16px;
        min-width: 64px;
        font-size: 14px;
        line-height: 40px;
        color: #646566;
        text-align: right;
    }

    .zent-form-control {
        display: flex;
        flex-direction: column;
        gap: 16px;


        .cert-type-desc-principal {
            padding: 16px;
            font-size: 14px;
            background-color: #f7f8fa;
            color: #646566;
            line-height: 20px;
            box-sizing: border-box;
        }
    }

    .zent-grid-table {
        border-collapse: collapse;

        colgroup {
            display: table-column-group;
            unicode-bidi: isolate;

            col {
                display: table-column;
                unicode-bidi: isolate;
            }
        }

        .zent-grid-thead {
            .zent-grid-tr {
                background-color: #f7f7f7;
                display: table-row;
                height: 56px;
            }
        }

        tr {
            border: 1px solid #ebedf0;

            th {
                border: 1px solid #ebedf0;
                padding: 18px 16px;
            }

            td {
                border: 1px solid #ebedf0;
                padding: 18px 16px;
                font-size: 14px;
                line-height: 1.8;
            }
        }

        .intro-column-title {
            font-size: 14px;
            line-height: 22px;
            color: #39393a;
            font-weight: bold;

            .sub-title {
                font-size: 14px;
                line-height: 20px;
                color: #9b9c9d;
                font-weight: normal;
            }
        }
    }
}

.one-item {
    display: flex;
    flex-direction: column;
    gap: 20px;

    .to-time {
        display: flex;
        align-items: center;
        gap: 20px;
    }
}

.required {
    color: var(--el-color-danger);
    margin-right: 4px;
}

.font-color {
    color: var(--tig-primary);
    cursor: pointer;
}
</style>
